<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 用户列表主体 -->
    <el-card>
      <!-- :gutter：间隔属性 -->
      <el-row :gutter="25">
        <!-- 搜索区域 -->
        <el-col :span="10">
          <!-- clearable: 清理按钮 -->
          <el-input placeholder="请输入搜索内容" v-model="filter.query" clearable>
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="14">
          <el-button type="primary" @click="showAddDialog()" style="float: right;">添加用户</el-button>
        </el-col>
        <el-table :data="userList" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="100"> </el-table-column>
          <el-table-column prop="username" label="用户名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column :formatter="formatterRole" label="权限"></el-table-column>
          <el-table-column label="状态">
            <!-- 开关组件 scope.row:当前行数据 -->
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.isState"
                @change="updateState(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template slot-scope="scope">
              <!-- 文本提示 -->
              <el-tooltip
                effect="dark"
                content="修改"
                placement="top-start"
                :enterable="false"
              >
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="showUpdateDialog(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="删除"
                placement="top-start"
                :enterable="false"
              >
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUser(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 
          分页组件 
          @size-change 每页最大变化数
          @current-change 当前页面变化数
          :current-page 当前页面
          layout 功能组件
        -->
        <div class="block">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="filter.pageNumber"
            :page-sizes="[1, 5, 10, 100]"
            :page-size="filter.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-row>
    </el-card>
    <!-- 添加设备 Dialog 对话框 -->
    <el-dialog
      title="添加设备"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closedAddDialog()"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser()">添加</el-button>
      </span>
    </el-dialog>
    <!-- 修改设备 Dialog 对话框 -->
    <el-dialog
      title="修改设备"
      :visible.sync="updDialogVisible"
      width="50%"
      @close="closedUpdDialog()"
    >
      <el-form :model="updForm" :rules="updFormRules" ref="updFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="updForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="updForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updForm.email"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="role">
          <template>
            <el-select v-model="updForm.role" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in roleOptions"
                :key="item.role"
                :label="item.name"
                :value="item.role">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateUser()">修改</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validateSpechars = (rule, value, callback) => {
      if (!this.checkSpecialKey(value)) {
        callback(new Error("不能含有特殊字符！"));
      } else {
        callback();
      }
    };
    var validateNewPassword = (rule, value, callback) => {
      if(value != this.updOldPassword){
        if(value.length < 4 || value.length > 8){
          return callback(new Error("长度在 4 到 8 个字符"));
        }
      }
      callback();
    };
    return {
      filter: {
        query: "",
        pageNumber: 1,
        pageSize: 5,
      },
      userList: [],
      total: 0,
      roleMeaning: {
        100: "管理员",
        200: "用户",
      },
      addDialogVisible: false, // 对话框状态
      updDialogVisible: false, // 对话框状态
      addForm: {
        // 添加的用户对象
        username: "",
        password: "",
        email: "",
        role: 200,
        state: 0,
      },
      updForm:{},
      updOldPassword:"",
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
          { validator: validateSpechars, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 4, max: 8, message: "长度在 4 到 8 个字符", trigger: "blur" },
        ],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
        ],
      },
      updFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" },
          { validator: validateSpechars, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validateNewPassword, trigger: "blur" },
        ],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
        ],
        role:[
          { required: true, message: "请选择权限", trigger: "blur" },
        ],
      },
      roleOptions:[
        {role:100,name:"管理员"},
        {role:200,name:"用户"},
      ]
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    checkSpecialKey(str) {
      var specialKey = "[`~!#$^&*()=|{}'\":;'\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'";
      for (var i = 0; i < str.length; i++) {
        if (specialKey.indexOf(str.substr(i, 1)) != -1) {
          return false;
        }
      }
      return true;
    },
    // 获取所有用户
    async getUserList() {
      const { data: res } = await this.$http.post("/queryUser", this.filter);
      if (res.flag == "OK") {
        var queryInfo = JSON.parse(res.data);
        this.userList = this.parseUserList(queryInfo.data);
        this.total = queryInfo.total;
      }
    },
    parseUserList(list) {
      var arr = [];
      if (list) {
        list.forEach(function (item) {
          if (item.state == 1) {
            item.isState = true;
          } else {
            item.isState = false;
          }
          arr.push(item);
        });
      }
      return arr;
    },
    formatterRole(row) {
      var result = this.roleMeaning[row.role];
      return result;
    },
    // 页面最大数量变化事件
    handleSizeChange(newSize) {
      this.filter.pageSize = newSize;
    },
    // 页码变化事件
    handleCurrentChange(newPage) {
      this.filter.pageNumber = newPage;
    },
    // 修改用户状态
    async updateState(row) {
      // 获取状态值

      var dataEncrypt = this.$encrypt.encrypt({
        id: row.id,
        state: this.getStateValue(row.isState),
      });
      // 加密请求
      const { data: res } = await this.$http.post("/updateState", dataEncrypt);
      if (res.flag == "OK") {
        this.$message.success("修改成功！");
      } else {
        this.$message.error("修改失败！");
      }
    },
    getStateValue(isState) {
      var state = 0;
      if (isState == true) {
        state = 1;
      }
      return state;
    },
    //打开对话框
    showAddDialog() {
      this.addDialogVisible = true;
    },
    //关闭对话框
    closedAddDialog() {
      this.$refs.addFormRef.resetFields();
      this.addDialogVisible = false;
    },
    closedUpdDialog() {
      this.$refs.updFormRef.resetFields();
      this.updDialogVisible = false;
    },
    //添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;

        var dataEncrypt = this.$encrypt.encrypt(this.addForm);
        const { data: res } = await this.$http.post("/addUser", dataEncrypt);
        if (res.flag == "OK") {
          this.$message.success("添加成功！");
          this.getUserList();
          this.closedAddDialog();
        } else {
          this.$message.error("添加失败！");
        }
      });
    },
    //删除用户
    deleteUser(row) {
      this.$confirm('是否删除'+row.username+'?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          var dataEncrypt = this.$encrypt.encrypt(row.id);
          // 加密请求
          const { data: res } = await this.$http.post("/delUser", dataEncrypt);
          if (res.flag == "OK") {
            this.$message.success("删除成功！");
            this.getUserList();
          } else {
            this.$message.error("删除失败！");
          }
        }).catch(() => {});
    },
    //显示修改用户
    async showUpdateDialog(row){
      var dataEncrypt = this.$encrypt.encrypt(row.id);
          // 加密请求
          const { data: res } = await this.$http.post("/getUser", dataEncrypt);
          if (res.flag == "OK") {
            this.updDialogVisible = true;
            this.updForm = this.$encrypt.decrypt(res);
            this.updOldPassword = this.updForm.password;
          }
    },
    //修改用户
    updateUser() {
      this.$refs.updFormRef.validate(async (valid) => {
        if (!valid) return;

        var dataEncrypt = this.$encrypt.encrypt(this.updForm);
        const { data: res } = await this.$http.post("/updateUser", dataEncrypt);
        if (res.flag == "OK") {
          this.$message.success("修改成功！");
          this.getUserList();
          this.closedUpdDialog();
        } else {
          this.$message.error("修改失败！");
        }
      });
    }
  },
  // 值变化调用函数
  watch: {
    //声明监听函数，调用查询函数
    filterQuery(curval, oldval) {
      this.getUserList();
    },
  },
  computed: {
    //计算器属性监听值变化
    filterQuery: function () {
      return this.filter.query + "" + this.filter.pageNumber + "" + this.filter.pageSize;
    },
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
  font-size: 17px;
}
.el-pagination{
  margin-top: 15px;
}
</style>
